//
//  Status.swift
//  MySinaWeiBo
//
//  Created by zhangfuwei on 15/8/3.
//  Copyright © 2015年 zhangfuwei. All rights reserved.
//

import UIKit

class Status: NSObject {
    //微博创建时间
    var created_at: String?
    // 微博ID
    var  id: Int = 0
    
    // 微博来源
    var source: String?
    
    // 微博信息内容
    var text: String?

    // 微博配图
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            
            if pic_urls?.count == 0 {
                return
            }
            //  MARK: ----一定要实例化
            storedURLs = [NSURL]()
            
            for dict in pic_urls! {
                 if let urlString = dict["thumbnail_pic"] as? String {
                    
                    let url = NSURL(string: urlString)
                    storedURLs?.append(url!)
                }
            }
        }
    }
    
    ///  图片地址存储
    var storedURLs:[NSURL]?
    
    var pictureURLs:[NSURL]? {
        return retweeted_status != nil ? retweeted_status?.storedURLs : storedURLs
    }
    
    
    // 用户
    var user: User?
    
    /// 转发微博
    var retweeted_status: Status?
    
    ///  添加一个 rowHeight 属性放在模型里
    var rowHeight: CGFloat?
    
    
    // MARK: 加载微博数据
    class func loadStatus( since_id: Int?, max_id: Int?,finished:(datalist: [Status]?,error : NSError?) ->()) {
        
        NetworkTools.sharedTools.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
            //  如果有错误
            if error != nil {
                finished(datalist: nil, error: error )
                return
            }
            
            //  如果有数据
            if let array = result?["statuses"] as? [[String: AnyObject]] {
                
                var list = [Status]()
                for dict in array {
                    
                    list.append(Status(dict: dict))
                }
                
                finished(datalist: list, error: nil)
            
                // 没错误,也没数据
            }else {
                finished(datalist: nil, error: nil)
            }
        }
        
    }
    
    //  重构函数
    init(dict:[String : AnyObject]) {
       super.init()
       setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    //  模型嵌套,当键为 user 时,使用 User 模型
    override func setValue(value: AnyObject?, forKey key: String) {
        
        if  key == "user" {
            
            if let dict = value as? [String:AnyObject] {
                
                user = User(dict: dict)
            }
            return
        }
        
        if  key == "retweeted_status" {
            
            if let dict = value as? [String:AnyObject] {
                
                retweeted_status = Status(dict: dict)
            }
            return
        }
        
        super.setValue(value, forKey: key)
    }

}
